package com.fang.security.security.service;

import com.fang.security.entity.DO.SysUser;
import com.fang.security.service.SysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
/**
 * @Author Bernie
 * @Description 自定义登录验证
 * @Date 16:14 2024/4/23
 **/
@Component
public class SecurityAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private SysUserService sysUserService;

//    @Resource
//    private AuthorityService authorityService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String username = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();

        //根据用户名查询用户
        SysUser sysUser = sysUserService.selectByName(username);
        if (sysUser == null) {
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        // 我们还要判断密码是否正确，这里我们的密码使用BCryptPasswordEncoder进行加密的
        if (!new BCryptPasswordEncoder().matches(password, sysUser.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
//        // 还可以加一些其他信息的判断，比如用户账号已停用等判断
//        if (!sysUser.getNotExpired()){
//            throw new LockedException("该用户已被冻结");
//        }

//        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        // 获取该用户所拥有的权限
//        List<UserRole> userRoles = authorityService.selectUserRoleByUserID(sysUser.getUserId());
//        // 声明用户授权
//        // 角色需要添加前缀："ROLE_"
//        userRoles.forEach(userRole -> {
//            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(CommonConstants.Role.NAME_PREFIX + userRole.getRoleCode());
//            grantedAuthorities.add(grantedAuthority);
//        });
//        return new UsernamePasswordAuthenticationToken(sysUser, password, grantedAuthorities);
        // 进行登录
        return new UsernamePasswordAuthenticationToken(sysUser, password, null);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}